<template>
  <el-form
    :model="form"
    ref="formRef"
    label-width="auto"
    style="max-width: 640px"
  >
    <el-form-item
      label="Accident title:"
      prop="title"
      :rules="{
        required: true,
        message: 'accident title can not be null',
        trigger: 'blur',
      }"
    >
      <el-input v-model="form.title" />
    </el-form-item>
    <el-form-item
      label="Accident title en:"
      prop="title"
      :rules="{
        required: false,
        message: 'accident title en can not be null',
        trigger: 'blur',
      }"
    >
      <el-input v-model="form.title_en" />
    </el-form-item>
    <el-form-item
      label="Year:"
      prop="year"
      :rules="{
        required: true,
        message: 'can not be null',
        trigger: 'blur',
      }"
    >
      <el-input v-model="form.year" />
    </el-form-item>
    <el-form-item
      label="Accident location:"
      prop="location"
      :rules="{
        required: true,
        message: 'can not be null',
        trigger: 'blur',
      }"
    >
      <el-input v-model="form.location" />
    </el-form-item>
    <el-form-item
      label="Accident death toll:"
      prop="death_toll"
      :rules="{
        required: false,
        message: '',
        trigger: 'blur',
      }"
    >
      <el-input-number :min="0" v-model="form.dead" />
    </el-form-item>
    <el-form-item
      label="Injure toll:"
      prop="injure_toll"
      :rules="{
        required: false,
        message: '',
        trigger: 'blur',
      }"
    >
      <el-input-number :min="0" v-model="form.injure" />
    </el-form-item>
    <el-form-item
      label="degree:"
      prop="degree"
      :rules="{
        required: false,
        message: '',
        trigger: 'blur',
      }"
    >
      <el-input-number :min="0" v-model="form.degree" />
    </el-form-item>
    <el-form-item label="Season">
      <el-select v-model="form.season" placeholder="please select season">
        <el-option label="Spring" value="1" />
        <el-option label="Summer" value="2" />
        <el-option label="Autumn" value="3" />
        <el-option label="Winter" value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="used chemical:">
      <el-select
        v-model="form.chemicals"
        filterable
        multiple
        placeholder="please select chemical"
      >
        <el-option
          v-for="item in chemicals"
          :key="item.Id"
          :label="item.Name"
          :value="item.Id"
        >
          <span style="float: left">{{ item.Name }}</span>
          <span
            style="
              float: right;
              color: var(--el-text-color-secondary);
              font-size: 13px;
            "
          >
            {{ item.DictName }}
          </span>
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="used equipment:">
      <el-select
        v-model="form.equipments"
        filterable
        multiple
        placeholder="please select equipment"
      >
        <el-option
          v-for="item in equipments"
          :key="item.Id"
          :label="item.Name"
          :value="item.Id"
        >
          <span style="float: left">{{ item.Name }}</span>
          <span
            style="
              float: right;
              color: var(--el-text-color-secondary);
              font-size: 13px;
            "
          >
            {{ item.DictName }}
          </span>
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="used consumable:">
      <el-select
        v-model="form.consumables"
        filterable
        multiple
        :reserve-keyword="false"
        placeholder="please select consumable"
      >
        <el-option
          v-for="item in consumables"
          :key="item.Id"
          :label="item.Name"
          :value="item.Id"
        >
          <span style="float: left">{{ item.Name }}</span>
          <span
            style="
              float: right;
              color: var(--el-text-color-secondary);
              font-size: 13px;
            "
          >
            {{ item.DictName }}
          </span>
        </el-option>
      </el-select>
    </el-form-item>
    <el-divider border-style="dashed" />
    <el-form-item
      required="true"
      label="description desc:"
      prop="description"
      :rules="{
        required: false,
        message: 'please input accident description',
        trigger: 'blur',
      }"
    >
      <el-input
        v-model="form.description"
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4 }"
        maxlength="300"
      />
    </el-form-item>
    <el-form-item
      label="description desc en:"
      prop="description_en"
      :rules="{
        required: false,
        message: 'please input accident description en',
        trigger: 'blur',
      }"
    >
      <el-input v-model="form.description_en" type="textarea" />
    </el-form-item>
    <el-form-item
      label="if need encrypt:"
      prop="need_encrypt"
      :rules="{
        required: false,
        message: 'please input accident description en',
        trigger: 'blur',
      }"
    >
      <el-switch
        v-model="need_encrypt"
        class="mt-2"
        style="margin-left: 0"
        inline-prompt
        :active-icon="Check"
        :inactive-icon="Close"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit(formRef)">Create</el-button>
      <el-button @click="onCancel(false)">Cancel</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import axios from "axios";
import { reactive, ref, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import api from "@/utils/axiosInstance";
import { ElMessage } from "element-plus";
import { Check, Close } from "@element-plus/icons-vue";

const need_encrypt = ref(true);

let loading = ref(false);
const formRef = ref<FormInstance>();

const props = defineProps(["showForm"]);
const emit = defineEmits(["update:modelValue"]);

const onCancel = (newValue: any) => {
  emit("update:modelValue", newValue);
};

const checked1 = ref(true);

let chemicals = ref([] as any[]);
let consumables = ref([] as any[]);
let equipments = ref([] as any[]);
// 在组件挂载后发起请求
onMounted(async () => {
  try {
    // 发起 GET 请求
    const chemicalResponse = await api.post("/chemical/select");
    const consumableResponse = await api.post("/consumable/select");
    const equipmentResponse = await api.post("/equipment/select");
    // 将响应数据赋值
    chemicals.value = chemicalResponse.data;
    consumables.value = consumableResponse.data;
    equipments.value = equipmentResponse.data;
  } catch (err) {
    // 捕获错误并赋值给 error
  } finally {
    // 请求完成，将 loading 状态设置为 false
    // loading.value = false;
  }
});

// do not use same name with ref
const form = reactive({
  title: "",
  title_en: "",
  description: "",
  description_en: "",
  year: "",
  location: "",
  dead: "",
  injure: "",
  degree: "",
  season: "",
  equipments: [],
  consumables: [],
  chemicals: [],
});

const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");
      loading.value = true;
      api
        .post("/accident/create", form)
        .then((response) => {
          // 处理API响应
          if (response.status == 200) {
            ElMessage({
              message: "Successfully added an accident record!",
              type: "success",
            });
          } else {
            ElMessage({
              message: "Failed to add an accident record!",
              type: "error",
            });
          }
          onCancel(false);
        })
        .catch((error) => {
          // 处理错误
          ElMessage({
            message: "Failed to add an accident record!",
            type: "error",
          });
          console.log(error, "error");
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      console.log("error submit!");
      return;
    }
  });
};
</script>
